<template>
  <view>
    <!-- 搜索框 -->
    <view class="search-container">
      <uni-search-bar @input="input" cancelButton="none" radius="24" focus="true"></uni-search-bar>
    </view>
    <!-- 搜索历史 -->
    <view class="search-history" v-if="searchResults.length === 0">
      <!-- title -->
      <view class="search-title">
        <text>搜索历史</text>
        <uni-icons type="trash" @click="clearHistory"></uni-icons>
      </view>
      <!-- history -->
      <view class="search-history">
        <uni-tag :text="item" v-for="(item, i) in searchHistory" :key="i" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>
    
    <!-- 关键词搜索列表 -->
    <view class="search-results-list" v-else>
      <!-- 搜索结果item -->
      <view class="search-results-item" v-for="(item, i) in searchResults" :key="i" @click="gotoGoodsDetail(item)">
        <view class="search-results-item-name">
          {{item.goods_name}}
        </view>
        <uni-icons type="arrowright"></uni-icons>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timerId: null, // 防抖timerId
        kw: '', //搜索关键词
        searchResults: [], // 关键词搜索列表
        searchHistory:[], // 搜索历史
      };
    },
    
    onLoad() {
      // 初始化搜索历史
      this.searchHistory = JSON.parse( uni.getStorageSync('history') || '[]' )
    },
    
    methods: {
      // 搜索框输入事件处理函数
      input(value){
        clearTimeout(this.timerId)
        // 设置防抖处理函数
        this.timerId = setTimeout(() => {
          // 发起请求
          console.log(value)
          // 搜索关键词判断
          if(!value.trim()){
            // 清空搜索结果列表
            this.searchResults =[]
            return
          }
          // 设置搜索关键词
          this.kw = value
          // 发起关键词搜索
          this.getSearchResults()
          
          // 保存搜索历史关键词
          this.saveSearchHistory()
        }, 500)

      },
      // 关键词搜索
      async getSearchResults(){
        const { data: res } = await uni.$http.get('/goods/qsearch', {query: this.kw})
        console.log(res)
        // 异常数据判断处理
        if(res.meta.status !== 200) return uni.$showMsg()
        // 设置data数据
        this.searchResults = res.message
      },
      // 点击关键词搜索item跳转到商品详情页
      gotoGoodsDetail(item){
        uni.navigateTo({
          url: `/subpkg/goods_detail/goods_detail?goods_id=${item.goods_id}`
        })
      },
      // 保存搜索关键词到搜索历史
      saveSearchHistory(){
        // this.searchHistory.unshift(this.kw)
        const index = this.searchHistory.indexOf(this.kw)
        if(index < 0){ // 如果搜索关键词不存在放到首位
          this.searchHistory = [this.kw, ...this.searchHistory]
        }else{// 否则将原来位置的关键词删掉，放到首位
          this.searchHistory.splice(index, 1)
          this.searchHistory = [this.kw, ...this.searchHistory]
        }
        // 保存数据到本地
        uni.setStorageSync('history', JSON.stringify(this.searchHistory))
        
      },
      // 清空搜索历史记录
      clearHistory(){
        this.searchHistory = []
        // 清空本地存储
        // uni.setStorageSync('history', '[]')
        uni.removeStorageSync('history')
      },
      
      // 跳转到商品列表页
      gotoGoodsList(item){
        uni.navigateTo({
          url: `/subpkg/goods_list/goods_list?query=${item}`
        })
      }
    }
  }
</script>

<style lang="scss">
  .search-container {
    background-color: #c00000;
    position: sticky;
    top: 0;
  }
  
  .search-history {
    .search-title{
      display: flex;
      height: 80rpx;
      align-items: center;
      justify-content: space-between;
      padding: 0 16rpx;
      border-bottom: 1rpx solid #efefef;
    }
    .search-history{
      .uni-tag {
        margin: 8rpx;
      }
    }
  }
  
  .search-results-list {
    .search-results-item{
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 84rpx;
      padding: 0 16rpx;
      border-bottom: 1rpx solid #efefef;
      .search-results-item-name{
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        font-size: 28rpx;
      }
    }
  }
</style>
